"""
API数据模型定义
使用Pydantic定义请求和响应模型
"""

from pydantic import BaseModel, Field, EmailStr
from typing import List, Dict, Any, Optional, Literal
from datetime import datetime
from enum import Enum
from sqlalchemy import Column, Integer, String, DateTime, Text, Float, Boolean, ForeignKey, JSON
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()

# ================================
# SQLAlchemy数据库模型
# ================================

class User(Base):
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True)
    email = Column(String(255), unique=True, index=True, nullable=False)
    username = Column(String(100), unique=True, index=True, nullable=False)
    hashed_password = Column(String(255), nullable=False)
    user_type = Column(String(20), nullable=False)  # "hr" or "candidate"
    company_id = Column(Integer, ForeignKey("companies.id"), nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    is_active = Column(Boolean, default=True)
    
    # 关系
    company = relationship("Company", back_populates="hr_users")
    candidate_profile = relationship("CandidateProfile", back_populates="user", uselist=False)
    hr_profile = relationship("HRProfile", back_populates="user", uselist=False)

class Company(Base):
    __tablename__ = "companies"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(255), nullable=False)
    description = Column(Text)
    industry = Column(String(100))
    size = Column(String(50))  # "startup", "small", "medium", "large"
    location = Column(String(255))
    website = Column(String(255))
    created_at = Column(DateTime, default=datetime.utcnow)
    
    # 关系
    hr_users = relationship("User", back_populates="company")
    job_positions = relationship("JobPosition", back_populates="company")

class HRProfile(Base):
    __tablename__ = "hr_profiles"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), unique=True)
    full_name = Column(String(255), nullable=False)
    position = Column(String(100))
    department = Column(String(100))
    phone = Column(String(20))
    preferences = Column(JSON)  # 筛选偏好配置
    
    # 关系
    user = relationship("User", back_populates="hr_profile")

class CandidateProfile(Base):
    __tablename__ = "candidate_profiles"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), unique=True)
    full_name = Column(String(255), nullable=False)
    phone = Column(String(20))
    location = Column(String(255))
    current_position = Column(String(255))
    experience_years = Column(Integer)
    skills = Column(JSON)  # 技能列表
    education = Column(JSON)  # 教育背景
    github_url = Column(String(255))
    linkedin_url = Column(String(255))
    portfolio_url = Column(String(255))
    
    # 关系
    user = relationship("User", back_populates="candidate_profile")
    resumes = relationship("Resume", back_populates="candidate")

class JobPosition(Base):
    __tablename__ = "job_positions"
    
    id = Column(Integer, primary_key=True, index=True)
    company_id = Column(Integer, ForeignKey("companies.id"))
    title = Column(String(255), nullable=False)
    description = Column(Text, nullable=False)
    requirements = Column(JSON)  # 技能要求列表
    experience_level = Column(String(50))  # "entry", "mid", "senior", "lead"
    salary_range = Column(String(100))
    location = Column(String(255))
    employment_type = Column(String(50))  # "full-time", "part-time", "contract"
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    
    # 关系
    company = relationship("Company", back_populates="job_positions")
    applications = relationship("JobApplication", back_populates="job_position")

class Resume(Base):
    __tablename__ = "resumes"
    
    id = Column(Integer, primary_key=True, index=True)
    candidate_id = Column(Integer, ForeignKey("candidate_profiles.id"))
    file_path = Column(String(500), nullable=False)
    original_filename = Column(String(255), nullable=False)
    parsed_content = Column(JSON)  # 解析后的结构化内容
    analysis_result = Column(JSON)  # AI分析结果
    score = Column(Float)  # 总体评分
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    candidate = relationship("CandidateProfile", back_populates="resumes")
    applications = relationship("JobApplication", back_populates="resume")

class JobApplication(Base):
    __tablename__ = "job_applications"
    
    id = Column(Integer, primary_key=True, index=True)
    job_position_id = Column(Integer, ForeignKey("job_positions.id"))
    resume_id = Column(Integer, ForeignKey("resumes.id"))
    candidate_id = Column(Integer, ForeignKey("candidate_profiles.id"))
    status = Column(String(50), default="pending")  # "pending", "screening", "interview", "rejected", "hired"
    match_score = Column(Float)  # 匹配评分
    hr_feedback = Column(Text)
    ai_analysis = Column(JSON)  # AI分析报告
    interview_notes = Column(Text)
    applied_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    job_position = relationship("JobPosition", back_populates="applications")
    resume = relationship("Resume", back_populates="applications")


# ================================
# 基础模型
# ================================

class BaseResponse(BaseModel):
    """基础响应模型"""
    timestamp: datetime = Field(default_factory=datetime.now)
    

class HealthResponse(BaseModel):
    """健康检查响应"""
    overall_health: str
    components: Dict[str, Any]
    issues: List[str] = []
    timestamp: datetime


class SystemStatusResponse(BaseModel):
    """系统状态响应"""
    initialized: bool
    orchestrator_status: Optional[Dict[str, Any]] = None
    specialists_status: Dict[str, Any] = {}
    tools_status: Dict[str, Any] = {}
    timestamp: datetime


# ================================
# 分析请求和响应模型
# ================================

class ResumeAnalysisRequest(BaseModel):
    """简历分析请求"""
    query: str = Field(..., description="简历分析查询或简历内容")
    job_requirements: Optional[str] = Field(None, description="职位要求")
    analysis_depth: Literal["basic", "detailed", "comprehensive"] = Field("detailed", description="分析深度")
    include_recommendations: bool = Field(True, description="是否包含建议")


class CandidateComparisonRequest(BaseModel):
    """候选人比较请求"""
    candidate_queries: List[str] = Field(..., description="候选人查询列表")
    job_requirements: Optional[str] = Field(None, description="职位要求")
    comparison_criteria: List[str] = Field(
        default=["skills", "experience", "education", "potential"],
        description="比较标准"
    )


class BackgroundCheckRequest(BaseModel):
    """背景核查请求"""
    candidate_info: str = Field(..., description="候选人信息")
    verification_depth: Literal["basic", "standard", "thorough"] = Field("standard", description="核查深度")
    check_social_media: bool = Field(False, description="是否检查社交媒体")
    verify_references: bool = Field(True, description="是否验证推荐人")


class PotentialAssessmentRequest(BaseModel):
    """潜力评估请求"""
    candidate_info: str = Field(..., description="候选人信息")
    assessment_dimensions: List[str] = Field(
        default=["learning_ability", "adaptability", "leadership_potential"],
        description="评估维度"
    )
    prediction_timeframe: Literal["short_term", "medium_term", "long_term"] = Field(
        "medium_term", 
        description="预测时间范围"
    )


class AnalysisResponse(BaseResponse):
    """分析响应"""
    task_id: str
    status: str
    result: Dict[str, Any]
    processing_time: Dict[str, float]


class ComparisonResponse(BaseResponse):
    """比较分析响应"""
    task_id: str
    status: str
    comparison_result: Dict[str, Any]
    candidates_analyzed: int
    processing_time: Dict[str, float]


class BackgroundCheckResponse(BaseResponse):
    """背景核查响应"""
    task_id: str
    status: str
    verification_result: Dict[str, Any]
    risk_level: str
    processing_time: Dict[str, float]


class PotentialAssessmentResponse(BaseResponse):
    """潜力评估响应"""
    task_id: str
    status: str
    assessment_result: Dict[str, Any]
    potential_score: float
    processing_time: Dict[str, float]


# ================================
# RAG查询模型
# ================================

class RAGQueryRequest(BaseModel):
    """RAG查询请求"""
    query: str = Field(..., description="查询问题")
    retrieval_modes: List[str] = Field(
        default=["vector", "keyword", "graph"],
        description="检索模式"
    )
    top_k: int = Field(10, description="检索结果数量", ge=1, le=50)
    rerank_top_k: int = Field(5, description="重排结果数量", ge=1, le=20)
    template_name: str = Field("general_qa", description="生成模板名称")
    return_intermediate: bool = Field(False, description="是否返回中间结果")


class SearchResultModel(BaseModel):
    """搜索结果模型"""
    document_id: str
    score: float
    relevance_type: str
    content_preview: str


class RAGQueryResponse(BaseResponse):
    """RAG查询响应"""
    query: str
    answer: str
    processing_time: Dict[str, float]
    search_results: Optional[List[SearchResultModel]] = None
    reranked_results: Optional[List[SearchResultModel]] = None


# ================================
# 数据管理模型
# ================================

class DataUploadRequest(BaseModel):
    """数据上传请求"""
    data_type: Literal["file_path", "directory", "huggingface_dataset"] = Field(..., description="数据类型")
    data_content: str = Field(..., description="数据内容（路径或数据集名称）")
    metadata: Optional[Dict[str, Any]] = Field(None, description="额外元数据")


class DataUploadResponse(BaseResponse):
    """数据上传响应"""
    upload_id: str
    status: str
    data_type: str
    message: str


class DataStatsResponse(BaseResponse):
    """数据统计响应"""
    pipeline_stats: Dict[str, Any]


# ================================
# 任务管理模型
# ================================

class TaskStatusResponse(BaseResponse):
    """任务状态响应"""
    task_id: str
    status: str
    description: str
    result: Optional[Dict[str, Any]] = None
    metadata: Optional[Dict[str, Any]] = None


# ================================
# 批量处理模型
# ================================

class BatchAnalysisRequest(BaseModel):
    """批量分析请求"""
    queries: List[str] = Field(..., description="查询列表")
    analysis_type: Literal["resume_analysis", "background_check", "potential_assessment"] = Field(
        "resume_analysis",
        description="分析类型"
    )
    batch_options: Dict[str, Any] = Field(default_factory=dict, description="批量选项")


class BatchAnalysisResponse(BaseResponse):
    """批量分析响应"""
    batch_id: str
    status: str
    total_queries: int
    message: str


# ================================
# 错误响应模型
# ================================

class ErrorResponse(BaseModel):
    """错误响应模型"""
    error: str
    detail: Optional[str] = None
    status_code: int
    timestamp: datetime


# ================================
# 配置和设置模型
# ================================

class SystemConfigModel(BaseModel):
    """系统配置模型"""
    retrieval_weights: Dict[str, float] = Field(
        default={"vector": 0.6, "keyword": 0.3, "graph": 0.1},
        description="检索权重配置"
    )
    agent_settings: Dict[str, Any] = Field(default_factory=dict, description="智能体设置")
    performance_settings: Dict[str, Any] = Field(default_factory=dict, description="性能设置")


class UpdateConfigRequest(BaseModel):
    """更新配置请求"""
    config_type: Literal["retrieval", "agent", "performance"]
    config_data: Dict[str, Any]


# ================================
# 统计和监控模型
# ================================

class UsageStats(BaseModel):
    """使用统计"""
    total_requests: int = 0
    successful_requests: int = 0
    failed_requests: int = 0
    average_response_time: float = 0.0
    peak_concurrent_users: int = 0


class PerformanceMetrics(BaseModel):
    """性能指标"""
    cpu_usage: float = 0.0
    memory_usage: float = 0.0
    disk_usage: float = 0.0
    active_tasks: int = 0
    queue_size: int = 0


class MonitoringResponse(BaseResponse):
    """监控响应"""
    usage_stats: UsageStats
    performance_metrics: PerformanceMetrics
    system_health: str


# ================================
# 专家智能体特定模型
# ================================

class ResumeAnalysisDetailRequest(BaseModel):
    """详细简历分析请求"""
    resume_content: str = Field(..., description="简历内容")
    job_description: Optional[str] = Field(None, description="职位描述")
    required_skills: List[str] = Field(default_factory=list, description="必需技能")
    preferred_experience: Optional[str] = Field(None, description="偏好经验")
    analysis_focus: List[str] = Field(
        default=["skills", "experience", "education", "cultural_fit"],
        description="分析重点"
    )


class SkillAssessmentRequest(BaseModel):
    """技能评估请求"""
    candidate_info: str = Field(..., description="候选人信息")
    target_skills: List[str] = Field(..., description="目标技能列表")
    skill_weights: Optional[Dict[str, float]] = Field(None, description="技能权重")


class CareerGrowthPredictionRequest(BaseModel):
    """职业成长预测请求"""
    candidate_profile: str = Field(..., description="候选人档案")
    current_role: str = Field(..., description="当前角色")
    target_role: Optional[str] = Field(None, description="目标角色")
    prediction_years: int = Field(3, description="预测年数", ge=1, le=10)


# ================================
# 高级分析模型
# ================================

class ComprehensiveAssessmentRequest(BaseModel):
    """综合评估请求"""
    candidate_data: Dict[str, Any] = Field(..., description="候选人完整数据")
    position_requirements: Dict[str, Any] = Field(..., description="职位要求")
    assessment_modules: List[str] = Field(
        default=["resume", "background", "potential", "cultural_fit"],
        description="评估模块"
    )
    weightings: Optional[Dict[str, float]] = Field(None, description="各模块权重")


class ComprehensiveAssessmentResponse(BaseResponse):
    """综合评估响应"""
    assessment_id: str
    overall_score: float
    module_scores: Dict[str, float]
    detailed_analysis: Dict[str, Any]
    recommendations: List[str]
    risk_factors: List[str]
    hiring_decision: str
    confidence_level: float


# ================================
# 实验性功能模型
# ================================

class ExperimentalFeatureRequest(BaseModel):
    """实验性功能请求"""
    feature_name: str = Field(..., description="功能名称")
    parameters: Dict[str, Any] = Field(default_factory=dict, description="参数")
    enable_logging: bool = Field(True, description="是否启用日志")


class ExperimentalFeatureResponse(BaseResponse):
    """实验性功能响应"""
    feature_name: str
    result: Any
    execution_time: float
    warnings: List[str] = []


# ================================
# HR和求职者系统专用模型
# ================================

# 枚举类型
class UserType(str, Enum):
    HR = "hr"
    CANDIDATE = "candidate"

class ApplicationStatus(str, Enum):
    PENDING = "pending"
    SCREENING = "screening"
    INTERVIEW = "interview"
    REJECTED = "rejected"
    HIRED = "hired"

class ExperienceLevel(str, Enum):
    ENTRY = "entry"
    MID = "mid"
    SENIOR = "senior"
    LEAD = "lead"

# 用户认证和管理
class UserCreate(BaseModel):
    """用户创建请求"""
    email: EmailStr
    username: str
    password: str
    user_type: UserType
    company_name: Optional[str] = None

class UserLogin(BaseModel):
    """用户登录请求"""
    username: str
    password: str

class UserResponse(BaseModel):
    """用户响应"""
    id: int
    email: str
    username: str
    user_type: str
    is_active: bool
    created_at: datetime
    
    class Config:
        from_attributes = True

class TokenResponse(BaseModel):
    """认证令牌响应"""
    access_token: str
    token_type: str = "bearer"
    expires_in: int
    user: UserResponse

# 候选人相关模型
class CandidateProfileCreate(BaseModel):
    """候选人档案创建"""
    full_name: str
    phone: Optional[str] = None
    location: Optional[str] = None
    current_position: Optional[str] = None
    experience_years: Optional[int] = None
    skills: List[str] = []
    education: List[Dict[str, Any]] = []
    github_url: Optional[str] = None
    linkedin_url: Optional[str] = None
    portfolio_url: Optional[str] = None

class CandidateProfileResponse(BaseModel):
    """候选人档案响应"""
    id: int
    full_name: str
    phone: Optional[str]
    location: Optional[str]
    current_position: Optional[str]
    experience_years: Optional[int]
    skills: List[str]
    education: List[Dict[str, Any]]
    github_url: Optional[str]
    linkedin_url: Optional[str]
    portfolio_url: Optional[str]
    
    class Config:
        from_attributes = True

# HR相关模型
class HRProfileCreate(BaseModel):
    """HR档案创建"""
    full_name: str
    position: Optional[str] = None
    department: Optional[str] = None
    phone: Optional[str] = None
    preferences: Dict[str, Any] = {}

class HRFilterPreferences(BaseModel):
    """HR筛选偏好设置"""
    min_experience_years: Optional[int] = None
    required_skills: List[str] = []
    preferred_skills: List[str] = []
    education_requirements: List[str] = []
    location_preferences: List[str] = []
    salary_range: Optional[Dict[str, int]] = None
    skill_weights: Dict[str, float] = {}

# 公司相关模型
class CompanyCreate(BaseModel):
    """公司创建"""
    name: str
    description: Optional[str] = None
    industry: Optional[str] = None
    size: Optional[str] = None
    location: Optional[str] = None
    website: Optional[str] = None

class CompanyResponse(BaseModel):
    """公司响应"""
    id: int
    name: str
    description: Optional[str]
    industry: Optional[str]
    size: Optional[str]
    location: Optional[str]
    website: Optional[str]
    
    class Config:
        from_attributes = True

# 职位相关模型
class JobPositionCreate(BaseModel):
    """职位创建"""
    title: str
    description: str
    requirements: List[str]
    experience_level: ExperienceLevel
    salary_range: Optional[str] = None
    location: Optional[str] = None
    employment_type: str = "full-time"

class JobPositionUpdate(BaseModel):
    """职位更新"""
    title: Optional[str] = None
    description: Optional[str] = None
    requirements: Optional[List[str]] = None
    experience_level: Optional[ExperienceLevel] = None
    salary_range: Optional[str] = None
    location: Optional[str] = None
    employment_type: Optional[str] = None
    is_active: Optional[bool] = None

class JobPositionResponse(BaseModel):
    """职位响应"""
    id: int
    title: str
    description: str
    requirements: List[str]
    experience_level: str
    salary_range: Optional[str]
    location: Optional[str]
    employment_type: str
    is_active: bool
    created_at: datetime
    company: CompanyResponse
    
    class Config:
        from_attributes = True

class JobSearchRequest(BaseModel):
    """职位搜索请求"""
    keywords: Optional[str] = None
    skills: Optional[List[str]] = None
    experience_level: Optional[ExperienceLevel] = None
    location: Optional[str] = None
    employment_type: Optional[str] = None
    company_size: Optional[str] = None
    salary_min: Optional[int] = None
    industry: Optional[str] = None
    limit: int = 20
    offset: int = 0

# 简历相关模型
class ResumeUploadResponse(BaseModel):
    """简历上传响应"""
    id: int
    original_filename: str
    file_path: str
    parsed_content: Dict[str, Any]
    analysis_result: Dict[str, Any]
    score: Optional[float]
    created_at: datetime

class ResumeAnalysisDetailResponse(BaseModel):
    """详细简历分析响应"""
    resume_id: int
    analysis_result: Dict[str, Any]
    score: float
    strengths: List[str]
    weaknesses: List[str]
    suggestions: List[str]
    skill_assessment: Dict[str, float]
    experience_evaluation: Dict[str, Any]
    background_verification: Dict[str, Any]
    potential_prediction: Dict[str, Any]

# 求职申请相关模型
class JobApplicationCreate(BaseModel):
    """求职申请创建"""
    job_position_id: int
    resume_id: int
    cover_letter: Optional[str] = None

class JobApplicationResponse(BaseModel):
    """求职申请响应"""
    id: int
    status: str
    match_score: Optional[float]
    ai_analysis: Dict[str, Any]
    applied_at: datetime
    job_position: JobPositionResponse
    hr_feedback: Optional[str]
    
    class Config:
        from_attributes = True

class ApplicationStatusUpdate(BaseModel):
    """申请状态更新"""
    status: ApplicationStatus
    hr_feedback: Optional[str] = None
    interview_notes: Optional[str] = None

# 候选人搜索和匹配
class CandidateSearchRequest(BaseModel):
    """候选人搜索请求"""
    skills: Optional[List[str]] = None
    experience_level: Optional[ExperienceLevel] = None
    location: Optional[str] = None
    min_score: Optional[float] = None
    job_position_id: Optional[int] = None
    limit: int = 10
    offset: int = 0

class CandidateMatchResult(BaseModel):
    """候选人匹配结果"""
    candidate: CandidateProfileResponse
    match_score: float
    matching_skills: List[str]
    missing_skills: List[str]
    strengths: List[str]
    recommendations: List[str]

# 职位匹配相关模型
class JobMatchRequest(BaseModel):
    """职位匹配请求"""
    candidate_id: Optional[int] = None
    job_ids: Optional[List[int]] = None
    limit: int = 5

class JobMatchResponse(BaseModel):
    """职位匹配响应"""
    job_position: JobPositionResponse
    match_score: float
    matching_skills: List[str]
    missing_skills: List[str]
    recommendations: List[str]
    interview_tips: List[str]

# 面试准备相关模型
class InterviewPrepRequest(BaseModel):
    """面试准备请求"""
    job_position_id: int
    candidate_id: Optional[int] = None

class InterviewPrepResponse(BaseModel):
    """面试准备响应"""
    company_info: Dict[str, Any]
    position_analysis: Dict[str, Any]
    likely_questions: List[str]
    preparation_tips: List[str]
    skill_gaps: List[str]
    improvement_suggestions: List[str]
    mock_interview_scenarios: List[Dict[str, Any]]

# 简历优化相关模型
class ResumeOptimizationRequest(BaseModel):
    """简历优化请求"""
    resume_id: int
    target_job_id: Optional[int] = None
    target_skills: Optional[List[str]] = None

class ResumeOptimizationResponse(BaseModel):
    """简历优化响应"""
    original_score: float
    optimized_content: str
    improvements: List[str]
    keyword_suggestions: List[str]
    structure_recommendations: List[str]
    ats_compatibility_score: float

# 批量操作模型
class BatchCandidateAnalysis(BaseModel):
    """批量候选人分析"""
    candidate_ids: List[int]
    job_position_id: Optional[int] = None
    analysis_depth: Literal["basic", "detailed", "comprehensive"] = "detailed"

class BatchAnalysisResult(BaseModel):
    """批量分析结果"""
    batch_id: str
    total_candidates: int
    processed_count: int
    results: List[Dict[str, Any]]
    summary_statistics: Dict[str, Any]

# GitHub验证相关模型
class GitHubVerificationRequest(BaseModel):
    """GitHub验证请求"""
    github_url: str
    candidate_id: Optional[int] = None

class GitHubVerificationResponse(BaseModel):
    """GitHub验证响应"""
    is_valid: bool
    repository_stats: Dict[str, Any]
    code_quality_score: float
    star_count: int
    contribution_analysis: Dict[str, Any]
    technology_stack: List[str]
    activity_level: str

# 统计和报告模型
class RecruitmentStatistics(BaseModel):
    """招聘统计"""
    total_applications: int
    pending_reviews: int
    interviews_scheduled: int
    offers_made: int
    average_processing_time: float
    top_skills_demand: List[Dict[str, Any]]
    conversion_rates: Dict[str, float]

class CandidateAnalyticsDashboard(BaseModel):
    """候选人分析仪表板"""
    profile_completeness: float
    skill_market_demand: Dict[str, float]
    salary_insights: Dict[str, Any]
    application_success_rate: float
    recommended_improvements: List[str]
    industry_trends: List[Dict[str, Any]]

# 智能推荐模型
class SmartRecommendationRequest(BaseModel):
    """智能推荐请求"""
    user_id: int
    recommendation_type: Literal["jobs", "candidates", "skills", "training"]
    context: Optional[Dict[str, Any]] = None

class SmartRecommendationResponse(BaseModel):
    """智能推荐响应"""
    recommendations: List[Dict[str, Any]]
    reasoning: List[str]
    confidence_scores: List[float]
    personalization_factors: List[str]